import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/api.dart";
import "package:ct_pa_majordomo/pages/device/entrance_guard/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ct_pa_majordomo/pages/apartment/associated_devices/widgets/associate_unbind_devices/index.dart";

class AssociatedRoom extends StatefulWidget {
  final int deviceId;
  final int roomId;
  final DeviceType deviceType;
  const AssociatedRoom({
    super.key, 
    required this.deviceId, 
    required this.roomId,
    required this.deviceType,
  });

  @override
  State<StatefulWidget> createState() => _AssociatedRoomState();

}

class _AssociatedRoomState extends State<AssociatedRoom> {

  List _list = [];
  Map _filter = {"pageNum": 1, "pageSize": 10, "name": ""};

  bool _associated() {
    return widget.roomId != -1;
  }

  bool _hasMore = true;
  bool _isLoading = false;

  // 获取未关联锁的房间列表
  Future<void> _getRooms({bool isRefresh = false}) async {
    if (_isLoading) return;
    
    if (isRefresh) {
      _filter["pageNum"] = 1;
      _hasMore = true;
    }

    if (!_hasMore) return;

    setState(() {
      _isLoading = true;
    });

    try {
      String type = widget.deviceType == DeviceType.lock ? '1' : '2';
      Map<String, dynamic> params = {
        ..._filter,
        "type": type,
      };
      Map resData = await apartmentApi.unboundDeviceRooms(type, params);
      List newList = resData["rows"] ?? [];
      
      setState(() {
        if (isRefresh) {
          _list = newList;
        } else {
          _list.addAll(newList);
        }
        
        _hasMore = newList.length >= _filter["pageSize"];
        if (_hasMore) {
          _filter["pageNum"] = _filter["pageNum"] + 1;
        }
      });
    } catch (error) {
      print(error);
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _getRoomInfo() async {
    try {
      Map resData = await apartmentApi.getRoomInfo(widget.roomId);
      setState(() {
        _list.add(resData["data"]);
      });
    } catch (error) {
      print(error);
    }
  }

  void _associatedRooms(Map roomInfo) async {
    String tip = "设备即将绑定房间：${roomInfo["name"]}";
    taiDialog(
      context: context,
      child: Text(tip, textAlign: TextAlign.center,),
      onConfirm: (taiContext) async {
        Navigator.of(taiContext).pop();
        EasyLoading.show();

        Map<String, dynamic> params = {
          "roomId": roomInfo["roomId"],
        };
        Map<String, dynamic> editNameParams = {};
        switch (widget.deviceType) {
          case DeviceType.lock: ///门锁
            params["lockId"] = widget.deviceId;
            await lockApi.bindRoom(params);
            editNameParams = {
              "lockId": widget.deviceId,
              "lockName": "${roomInfo["buildingName"] ?? ""}${roomInfo["name"]}",
            };
            await lockApi.editLock(editNameParams);
            break;
          case DeviceType.electricityMeter: ///电表
            params["id"] = widget.deviceId;
            await electricityMeterApi.bindRoom(params);
            editNameParams = {
              "electricityMeterId":widget.deviceId,
              "name": "${roomInfo["buildingName"]}${roomInfo["name"]}",
            };
            await electricityMeterApi.editElectricityMeter(editNameParams);
            break;
          case DeviceType.faceLock: /// 门禁
            params["faceLockId"] = widget.deviceId;
            params["roomIds"] = widget.roomId;
            await entranceGuardApi.bindRooms(params);
            break;
        }
        EasyLoading.dismiss();
        Stacker.pop(true);
      }
    );
  }

  void _unbindRoom() async {
    EasyLoading.show();
    if (widget.deviceType == DeviceType.lock) {
      await lockApi.unbindRoom(widget.deviceId);
    } else {
      await electricityMeterApi.unbindRoom(widget.deviceId);
    }
    EasyLoading.showToast("解绑成功");
    Stacker.pop(true);
  }

  // 添加加载更多方法
  Future<void> _onLoadMore() async {
    if (!_associated()) {
      await _getRooms();
    }
  }

  // 添加刷新方法
  Future<void> _onRefresh() async {
    if (!_associated()) {
      await _getRooms(isRefresh: true);
    }
  }

  @override
  void initState() {
    if (!_associated()) {
      _getRooms();
    } else {
      _getRoomInfo();
    }
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
      title: "关联的房间",
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      showSearch: false,
      showFloatBtn: false,
      children: [
        Container(
          padding: EdgeInsets.only(top: !_associated() ? 60 : 0, bottom: !_associated() ? 0 : 78),
          child: RefreshIndicator(
            onRefresh: _onRefresh,
            child: NotificationListener<ScrollNotification>(
              onNotification: (ScrollNotification scrollInfo) {
                if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent) {
                  _onLoadMore();
                }
                return true;
              },
              child: ListView.separated(
                itemBuilder: (context, index) {
                  return Container(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                    decoration: const BoxDecoration(
                      color: Colors.white,
                    ),
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: !_associated() ? () {
                        _associatedRooms(_list[index]);
                      } : null,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(_list[index]["name"]),
                          if (!_associated()) const Icon(Icons.circle_outlined, color: ThemeVars.colorPrimary,)
                        ],
                      ),
                    ),
                  );
                },
                separatorBuilder: (context, index) => const SolidDivider(padding: EdgeInsets.only(left: 12)),
                itemCount: _list.length
              ),
            ),
          ),
        ),
        if (!_associated()) Positioned(
            width: MediaQuery.of(context).size.width,
            top: 0,
            left: 0,
            child: Container(
                width: MediaQuery.of(context).size.width,
                decoration: const BoxDecoration(
                  color: ThemeVars.colorBackground,
                ),
                child: Column(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
                      decoration: const BoxDecoration(
                          color: Colors.white
                      ),
                      child: SizedBox(
                        height: 40,
                        child: TextFormField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(5)),
                                borderSide: BorderSide.none
                            ),
                            hintText: "请输入",
                            isDense: true,
                            filled: true,
                            fillColor: ThemeVars.colorBackground,
                            suffixIcon: SizedBox(
                              child: Icon(Icons.search, size: 20,),
                            ),
                          ),
                          style: TextStyle(fontSize: 14),
                          initialValue: _filter["name"],
                          onChanged: (value) {
                            setState(() {
                              _filter["name"] = value;
                              _filter["pageNum"] = 1;
                              _getRooms();
                            });
                          },
                        ),
                      ),
                    ),
                    const SizedBox(height: 10, child: DecoratedBox(decoration: BoxDecoration(color: ThemeVars.colorBackground)),)
                  ],
                )
            )
        ),
        if (_associated()) Positioned(
            bottom: 0,
            left: 0,
            width: MediaQuery.of(context).size.width,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 16),
              decoration: const BoxDecoration(
                  color: Colors.white,
                  boxShadow: [ThemeVars.boxShadow]
              ),
              child: Button(
                  type: ButtonType.primary,
                  onPressed: () {
                    _unbindRoom();
                  },
                  child: const Text("解除关联")
              ),
            )
        ),
        if (!_associated() && _isLoading) Positioned(
          bottom: 20,
          left: 0,
          right: 0,
          child: Center(
            child: CupertinoActivityIndicator(),
          ),
        ),
      ],
    );
  }

}